<script type="text/javascript">
var <?= $this->jqgrid->jsObject ?> = {

    resourceOptions: <?= $this->jqgrid->renderOptions() ?>,
    privOptions: <?= $this->subjqgrid->renderOptions() ?>,

    resources: {},
	curResources: {},
	dependents: {},
    actionOptions: null,

    roleId: null,
	gridId: "#<?= $this->jqgrid->tableId ?>",
	tblKey: 't',
	lastSubGridId: null,

	callback: {
		expand: {},
		collapse: {}
	},

    selectPrivilege: function(resourceId, privId, status) {
        if (true == status) {
            this.addPrivilege(resourceId, privId);
			this.resourceSetChecked(resourceId);
        } else  {
            this.deletePrilivege(resourceId, privId);
			if ($.isEmptyObject(this.resources[resourceId])) {
				this.deleteResource(resourceId);
				this.resourceSetUnchecked(resourceId);
			}
        }
    },

	selectAllPrivileges: function(resourceId, rowIds, status) {
		if (rowIds.length > 0 && rowIds[0] < 1) {
			rowIds.shift();
		}

		for (var i = 0; i < rowIds.length; i++) {
			this.selectPrivilege(resourceId, rowIds[i], status);
		}
	},

    selectResource: function(resourceId, status) {
        if (true == status) {
            this.addResource(resourceId);
			this.initPrivileges(resourceId);
        } else  {
			this.deletePrivileges(resourceId);
			this.deleteResource(resourceId);
        }
    },

	selectAllResources: function(rowIds, status) {
		if (rowIds.length > 0 && rowIds[0] < 1) {
			rowIds.shift();
		}

		for (var i = 0; i < rowIds.length; i++) {
			this.selectResource(rowIds[i], status);
		}
	},

    onSelectRow: function(rowId, status) {
        this.selectResource(rowId, status);
    },

	onSelectAll: function(rowIds, status) {
		this.selectAllResources(rowIds, status);
	},

	gridComplete: function(opt) {
        this.actionOptions = opt;
		this.initResources();
	},

    subGridRowExpanded: function(subgridId, rowId) {
        var obj = this;
        obj.rowId = rowId;

        var tableId = obj.lastSubGridId = subgridId + obj.tblKey;
        var options = $.extend({}, obj.privOptions);

        options = $.extend(options, {
            url: options.url + '?' + $.param({id: rowId}),
            onSelectRow: function(subRowId, status) {
                obj.selectPrivilege(rowId, subRowId, status);
            },
			onSelectAll: function(rowIds, status) {
				obj.selectAllPrivileges(rowId, rowIds, status);
			}
        });

		obj.addDependent(rowId, {
			subgridId: tableId
		});

		if (undefined !== obj.callback.expand[rowId]) {
			options.gridComplete = function() {
				obj.callback.expand[rowId](rowId);
			}
		}

        $("#" + subgridId).html("<div style='padding:5px'><table id='" + tableId + "' class='scroll'></table>");
        $("#" + tableId).jqGrid(options);

	},

	subGridRowColapsed: function(subgridId, rowId) {
		if (undefined !== this.resources[rowId]) {
			this.deletePrivileges(rowId);
			this.deleteResource(rowId);
			this.resourceSetUnchecked(rowId);
		}
		this.deleteDependent(rowId);
	},

	addDependent: function(resourceId, opt) {
		if (undefined === this.dependents[resourceId]) {
			this.dependents[resourceId] = opt;
		}
	},

	deleteDependent: function(resourceId) {
		if (undefined !== this.dependents[resourceId]) {
			delete this.dependents[resourceId];
		}
	},

    addResource: function(resourceId) {
		if (undefined === resourceId || resourceId < 1) return;
        if (undefined === this.resources[resourceId]) {
            this.resources[resourceId] = {};
        }
        return this.resources[resourceId];
    },

    deleteResource: function(resourceId) {
        if (undefined !== this.resources[resourceId]) {
            delete this.resources[resourceId];
        }
    },

	resourceSetChecked: function(resourceId) {
		var rs = $(this.gridId).jqGrid("getGridParam", "selarrrow");
		if ($.inArray(resourceId, rs) == -1) {
			$(this.gridId).jqGrid("setSelection", resourceId, false);
		}		
	},

	resourceSetUnchecked: function(resourceId) {
		var rs = $(this.gridId).jqGrid("getGridParam", "selarrrow");
		if ($.inArray(resourceId, rs) != -1) {
			$(this.gridId).jqGrid("setSelection", resourceId, false);
		}
	},

	initResources: function() {
        var obj = this;
        var opt = obj.actionOptions;

        if (undefined !== opt.rules) {
            var r = {};

            for (var i = 0; i < opt.rules.length; i++) {
                var rid = opt.rules[i][opt.rulesFormat['resource']];
                var pid = opt.rules[i][opt.rulesFormat['privilege']];

                if (undefined === r[rid]) {
                    this.addResource(rid);
                    this.resourceSetChecked(rid);
                    r[rid] = [];
                }

                r[rid].push(pid);
            }

            for (var n in r) {
                obj.callback.expand[n] = function(rid) {
                    var gridId = "#" + obj.dependents[rid]['subgridId'];
                    obj.addPrivileges(rid, r[rid]);

                    delete obj.callback.expand[rid];
                };

                $(obj.gridId).jqGrid("expandSubGridRow", n);
            }
        }
	},

    addPrivilege: function(resourceId, privId) {
		if (undefined === privId || privId < 1) return;
		var r = this.addResource(resourceId, true);
        if (undefined === r[privId]) {
            r[privId] = true;
        }
    },

    deletePrilivege: function(resourceId, privId) {
        if (undefined !== this.resources[resourceId]) {
            var r = this.resources[resourceId];
            if (undefined !== r[privId]) {
               delete r[privId];
            }
        }
    },

	privilegeSetChecked: function(resourceId, privId) {
		if (!this.dependents[resourceId]) return;
		var gridId = "#" + this.dependents[resourceId]['subgridId'];
		var rs = $(gridId).jqGrid("getGridParam", "selarrrow");
		if ($.inArray(privId, rs) == -1) {
			$(gridId).jqGrid("setSelection", privId, false);
		}
	},

	privilegeSetUnchecked: function(resourceId, privId) {
		if (!this.dependents[resourceId]) return;
		var gridId = "#" + this.dependents[resourceId]['subgridId'];
		var rs = $(gridId).jqGrid("getGridParam", "selarrrow");
		if ($.inArray(privId, rs) != -1) {
			$(gridId).jqGrid("setSelection", privId, false);
		}
	},

	initPrivileges: function(resourceId) {
		if (undefined !== this.resources[resourceId]) {
			var obj = this;

			if (undefined === obj.dependents[resourceId]) {
				this.callback.expand[resourceId] = function() {
					var gridId = "#" + obj.dependents[resourceId]['subgridId'];
					var rs = $(gridId).jqGrid("getDataIDs");
					obj.addPrivileges(resourceId, rs);

					delete obj.callback.expand[resourceId];
				}

				$(this.gridId).jqGrid("expandSubGridRow", resourceId);

			} else {
				var gridId = obj.dependents[resourceId]['subgridId'];
				var rs = $("#" + gridId).jqGrid("getDataIDs");
				for (var i = 0; i < rs.length; i++) {
					obj.addPrivilege(resourceId, rs[i]);
					obj.privilegeSetChecked(resourceId, rs[i]);
				}
			}
		}
	},

	addPrivileges: function(resourceId, privIds) {
		for (var i = 0; i < privIds.length; i++) {
			this.addPrivilege(resourceId, privIds[i]);
			this.privilegeSetChecked(resourceId, privIds[i]);
		}
	},

	deletePrivileges: function(resourceId, privIds) {
		if (undefined !== this.resources[resourceId]) {
			if (!privIds) {
				privIds = [];
				for (var i in this.resources[resourceId]) {
					privIds.push(i);
				}
			}
			for (var i = 0; i < privIds.length; i++) {
				this.deletePrilivege(resourceId, privIds[i]);
				this.privilegeSetUnchecked(resourceId, privIds[i]);
			}
		}
	},

    saveResources: function() {
        var obj = this;
        var opt = obj.actionOptions;

        var q = obj.query(obj.resources);
        $.ajax({
            url: opt.saveUrl + '?' + $.param({nodeid: opt.roleId}),
            data: q,
            type: 'POST',
            success: function(data) {
                info_dialog("Сохранение", "Данные успешно сохранены", null, {width:"226px"});
            },
            error: function(req) {
                info_dialog("Ошибка", "Произошла ошибка при сохранении данных", null, {width:"226px"});
            }
        });
    },

    query: function(data) {
        var result = {id: {}}

        for (var i in data) {
            result.id[i] = [];
            for (var j in data[i]) {
                result.id[i].push(j);
            }
        }

        return result;
    },

    comeback: function() {
        if (this.actionOptions.backUrl) {
            location.href = this.actionOptions.backUrl;
        }
    }
}
</script>
<?= $this->jqgrid ?>